package com.feicheng.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.deser.impl.CreatorCandidate.Param;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.persistence.entity.Dept;
import com.feicheng.persistence.entity.Emp;
import com.feicheng.persistence.entity.Flow;
import com.feicheng.persistence.entity.Job;
import com.feicheng.persistence.entity.Step;
import com.feicheng.persistence.mapper.DeptMapper;
import com.feicheng.persistence.mapper.FlowMapper;
import com.feicheng.persistence.model.DeptPageModel;
import com.feicheng.persistence.model.EmpJobModel;
import com.feicheng.persistence.model.FlowModel;
import com.feicheng.persistence.model.FlowStepModel;
import com.feicheng.persistence.service.*;
import com.feicheng.persistence.service.impl.DeptServiceImpl;
import com.feicheng.service.IFOrgService;

import java.util.ArrayList;
import java.util.List;

//import java.awt.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class FOrgServiceImpl {

    @Autowired
    IEmpService iEmpService;

    @Autowired
    IDeptService iDeptService;

    @Autowired
    IFlowService iFlowService;

    @Autowired
    IStepService iStepService;

    @Autowired
    IFlowRecordService iFlowRecordService;

    @Autowired
    IStepRecordService iStepRecordService;

    @Autowired
    IJobService iJobService;
    
    @Autowired
    DeptMapper deptMapper;
    
    @Autowired
    FlowMapper flowMapper;

    /**
     * key: "/dept/all", 高宁
     * @param param
     * @return
     */
    public ResultInfo getDeptByAll(JSONObject param) {
    	//获取所传参数
    	String name = param.getString("name");
    	
    	List<Dept> depts = new ArrayList<Dept>();
    	
    	if(name == null) {	//如果参数为空，全查询
    		depts = iDeptService.list();
    	}else {
    		//如果参数不为空，按条件模糊全查询
    		QueryWrapper<Dept> deptWrapper = new QueryWrapper<Dept>();
    		deptWrapper.like("name", name);
    		depts = iDeptService.list(deptWrapper);
//    		//如果条件查询结果为空，则查询条件不存在
//    		if (null == depts || depts.size() == 0) {
//                throw new SystemException("1");
//            }
    	}

        return ResultInfo.success(depts);
    }

    /**
     * key: "/dept/page", 小伟
     * @param current
     * @param size
     * @param param
     * @return
     */
    public ResultInfo getDeptByPage(Integer current, Integer size, JSONObject param)
    {String name = param.getString("name");
    Page<DeptPageModel> deptPages = new Page<DeptPageModel>(current,size);
    
    QueryWrapper<Dept> queryWrapper = new QueryWrapper<Dept>();
    queryWrapper.like("name", name);
    

        return ResultInfo.success(deptMapper.getDeptPage(deptPages,queryWrapper));

    }

    /**
     * key: "/dept/info",delete 戴金钰
     * @param deptId
     * @return
     */
    @Transactional
    public ResultInfo deleteDept(Integer deptId) {
    	QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<Dept>();
    	deptQueryWrapper.eq("dept_id", deptId);
    	Long deptNum = iDeptService.count(deptQueryWrapper);
    	if(deptNum<=0) {
    		throw new SystemException("部门信息不存在");
    	}
    	iDeptService.remove(deptQueryWrapper);
        return ResultInfo.success();
    }

    /**
     * key: "/dept/info",get 戴金钰
     * @param deptId
     * @return
     */
    public ResultInfo getDept(Integer deptId) {
    	QueryWrapper<Dept> deptQueryWrapper = new QueryWrapper<>();
    	deptQueryWrapper.eq("dept_id", deptId);
    java.util.List<Dept> depts =  iDeptService.list(deptQueryWrapper);
    if (depts.size()<=0) {
//    	根据部门id没有找到部门信息
		throw new SystemException("1");
	}
    if (depts.size()>1) {
//    	根据部门id找到多个部门信息
		throw new SystemException("1");
	}
        return ResultInfo.success(depts.get(0));
    }

    /**
     * key: "/dept/info",put 辛松柏
     * @param
     * @return
     */
    public ResultInfo updateDept(JSONObject param) {
    	Dept dept = param.getObject("dept", Dept.class);
    	if (null == dept) {
    		throw new SystemException("1");
		}
    	boolean result = iDeptService.updateById(dept);
    	if (result != true) {
    		throw new SystemException("2");
		}
        return ResultInfo.success("修改成功");
    }

    /**
     * key: "/dept/info",post 辛松柏
     * @param
     * @return
     */
    public ResultInfo newDept(JSONObject param) {
    	Dept dept = param.getObject("dept", Dept.class);
    	
    	if(!StringUtils.hasLength(dept.getName())) {
    		throw new SystemException("部门名称未输入");
    	}
    	
    	iDeptService.save(dept);

    	if(null == dept.getDeptId()) {
    		throw new SystemException("部门新增失败");
    	}
    	
        return ResultInfo.success("部门新增成功");
        
    }

    /**
     * key: "/dept/flow/all",get  王子文
     * @param param
     * @return
     */
    public ResultInfo getFlowByAll(JSONObject param) {
    	Integer deptId = param.getInteger("deptId");
    	String name = param.getString("name");
    	Integer jobId = param.getInteger("jobId");
    	List<FlowModel> flowModels = flowMapper.getFlowByAll(deptId,name,jobId);
        return ResultInfo.success(flowModels);
    }

    /**
     * key: "/dept/flow/info",get 王子文
     * @param flowId
     * @return
     */
    public ResultInfo getFlow(Integer flowId) {
        if (null == flowId) {
            throw new SystemException("flowId为空");
        }
    	QueryWrapper<Flow> flowQueryWrapper = new QueryWrapper<>();
    	flowQueryWrapper.eq("flow_id", flowId);
    	QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<>();
    	stepQueryWrapper.eq("flow_id", flowId);
    	FlowStepModel flowStepModel = new FlowStepModel();
    	List<Flow> flowList = iFlowService.list(flowQueryWrapper);
    	if(flowList.size() <1) {
    		throw new SystemException("没有flowId对应数据");
    	}else if (flowList.size() > 1) {
    		throw new SystemException("有多条flowId对应数据");
		}else if(flowList.size() == 1) {
			List<Step> stepList = iStepService.list(stepQueryWrapper);
	    	flowStepModel.setFlow(flowList.get(0)); 
	    	flowStepModel.setSteps(stepList);
		}
        return ResultInfo.success(flowStepModel);
    }

    /**
     * key: "/dept/flow/info",post 王子文
     * @param param
     * @return
     */
    public synchronized ResultInfo newFlow(JSONObject param) {
    	QueryWrapper<Flow> flowQueryWrapper = new QueryWrapper<>();
    	Flow flowObject = param.getObject("flow", Flow.class);
    	List<Step> stepList = JSONArray.parseArray(param.getString("steps"), Step.class);
		if (null == flowObject) {
			throw new SystemException("flow对象为空");
		}
		if (null == flowObject.getDeptId()) {
			throw  new SystemException("deptId为空");
		}
		if (null == flowObject.getJobId()) {
			throw  new SystemException("jobId为空");
		}
		if (null == flowObject.getLevels()) {
			throw  new SystemException("levels为空");
		}
		if (!StringUtils.hasLength(flowObject.getName())) {
			throw  new SystemException("流程名称为空");
		}
		if (stepList.isEmpty()) {
			throw new SystemException("stepList为空");
		}else {
			for (int index = 0; index < stepList.size(); index++) {
				if(null == stepList.get(index).getJobId()) {
					throw  new SystemException("jobId为空");
				}
				if(null == stepList.get(index).getLevel()) {
					throw  new SystemException("level为空");
				}
				if(!StringUtils.hasLength(stepList.get(index).getName())) {
					throw  new SystemException("name为空");
				}
			}
		}
    	flowQueryWrapper.eq("dept_id", flowObject.getDeptId());
    	flowQueryWrapper.eq("job_id", flowObject.getJobId());
    	flowQueryWrapper.eq("levels", flowObject.getLevels());
    	flowQueryWrapper.eq("name", flowObject.getName());
		List<Flow> flowSaveBefore = iFlowService.list(flowQueryWrapper);
		if(flowSaveBefore.isEmpty()) {
			boolean flowResult = iFlowService.save(flowObject);
		}else {
			throw new SystemException("流程已存在");
		}
		List<Flow> flowSaveAfter = iFlowService.list(flowQueryWrapper);
		if(flowSaveAfter.size() == 1) {
	        for (int index = 0; index < stepList.size(); index++) {
	        	stepList.get(index).setFlowId(flowSaveAfter.get(0).getFlowId());
			}
		}else {
			throw new SystemException("1");
		}
		boolean stepResult = iStepService.saveBatch(stepList);
    	QueryWrapper<Step> stepQueryWrapper = new QueryWrapper<>();
    	stepQueryWrapper.eq("flow_id", flowSaveAfter.get(0).getFlowId());
    	List<Step> stepSaveAfter = iStepService.list(stepQueryWrapper);
		if(!(stepSaveAfter.size() == stepList.size())) {
	        UpdateWrapper<Flow> flowUpdateWrapper = new UpdateWrapper<>();
	        flowUpdateWrapper.eq("flow_id", flowSaveAfter.get(0).getFlowId());
			boolean flowRemove = iFlowService.remove(flowUpdateWrapper);
			throw new SystemException("1");
		}
        return ResultInfo.success();
    }

    /**
     * key: "/dept/flow/info", put 王子文
     * @param param
     * @return
     */
    @Transactional
    public synchronized ResultInfo updateFlow(JSONObject param) {
    	Flow flowObject = param.getObject("flow", Flow.class);
    	List<Step> stepList = JSONArray.parseArray(param.getString("steps"), Step.class);
		if (null == flowObject) {
			throw new SystemException("flow对象为空");
		}
		if (null == flowObject.getFlowId()) {
			throw  new SystemException("flowId为空");
		}
		if (null == flowObject.getDeptId()) {
			throw  new SystemException("deptId为空");
		}
		if (null == flowObject.getDeptId()) {
			throw  new SystemException("deptId为空");
		}
		if (null == flowObject.getJobId()) {
			throw  new SystemException("jobId为空");
		}
		if (null == flowObject.getLevels()) {
			throw  new SystemException("levels为空");
		}
		if (!StringUtils.hasLength(flowObject.getName())) {
			throw  new SystemException("流程名称为空");
		}
		if (stepList.isEmpty()) {
			throw new SystemException("stepList为空");
		}else {
			for (int index = 0; index < stepList.size(); index++) {
				if(null == stepList.get(index).getFlowId()) {
					throw  new SystemException("flowId为空");
				}
				if(null == stepList.get(index).getJobId()) {
					throw  new SystemException("jobId为空");
				}
				if(null == stepList.get(index).getLevel()) {
					throw  new SystemException("level为空");
				}
				if(!StringUtils.hasLength(stepList.get(index).getName())) {
					throw  new SystemException("name为空");
				}
			}
		}
    	QueryWrapper<Flow> flowQueryWrapper = new QueryWrapper<>();
    	flowQueryWrapper.eq("flow_id", flowObject.getFlowId());
    	iFlowService.update(flowObject, flowQueryWrapper);
        UpdateWrapper<Step> stepWrapper = new UpdateWrapper<>();
        stepWrapper.eq("flow_id", flowObject.getFlowId());
        boolean stepRemove = iStepService.remove(stepWrapper);
		boolean stepSave = iStepService.saveBatch(stepList);
        return ResultInfo.success();
    }

    /**
     * key: "/dept/flow/info", delete 王子文
     * @param flowId
     * @return
     */
    @Transactional
    public ResultInfo deleteFlow(Integer flowId) {
        if (null == flowId) {
            throw new SystemException("1");
        }
        UpdateWrapper<Step> stepWrapper = new UpdateWrapper<>();
        stepWrapper.eq("flow_id", flowId);
        UpdateWrapper<Flow> flowWrapper = new UpdateWrapper<>();
        flowWrapper.eq("flow_id", flowId);
        boolean stepResult = iStepService.remove(stepWrapper);
		boolean flowResult = iFlowService.remove(flowWrapper);
        return ResultInfo.success();
    }
    
    /**
     * key: "/dept/job/all",get 朱禹成
     * @param param
     * @return
     */
    @Transactional
    public ResultInfo getJobByAll(JSONObject param) {
    	Integer deptId = param.getInteger("deptId");
    	Integer pJobId = param.getInteger("pJobId");
    	
    	QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
    	if(null != deptId) {
    		queryWrapper.eq("job.dept_id", deptId);
    	}
    	if(null != pJobId) {
    		queryWrapper.eq("p_job_id", pJobId);
    	}
    	
    	List<Job> jobList = iJobService.list(queryWrapper);
        return ResultInfo.success(jobList);
    }

    /**
     * key: "/dept/job/info",get 朱禹成
     * @param jobId
     * @return
     */
    @Transactional
    public ResultInfo getJob(Integer jobId) {
    	if(jobId == null || jobId == 0) {
    		throw new SystemException("1");
    	}
    	QueryWrapper<Job> queryWrapper = new QueryWrapper<Job>();
    	queryWrapper.eq("job_id", jobId);
    	
    	List<Job> jobList = iJobService.list(queryWrapper);
    	if(!(jobList.size() == 1)) {
    		throw new SystemException("1");
    	}
    	Job job = jobList.get(0);
        return ResultInfo.success(job);
    }


    /**
     * key: "/dept/job/info",post 朱禹成
     * @param param
     * @return
     */
    @Transactional
    public ResultInfo newJob(JSONObject param) {
    	Integer deptId = param.getInteger("deptId");
    	String name = param.getString("name");
    	Integer pJobId = param.getInteger("pJobId");
    	if(deptId == null || name == null || pJobId == null || deptId == 0 || pJobId < 0) {
    		throw new SystemException("请完整填写");
    	}
    	Job job = new Job();
    	job.setDeptId(deptId);
    	job.setName(name);
    	job.setPJobId(pJobId);
    	Boolean statusBoolean = iJobService.save(job);
        return ResultInfo.success();
    }

    /**
     * key: "/dept/job/info", put 朱禹成
     * @param param
     * @return
     */
    @Transactional
    public ResultInfo updateJob(JSONObject param) {
    	Integer jobId = param.getInteger("jobId");
    	Integer deptId = param.getInteger("deptId");
    	String name = param.getString("name");
    	Integer pJobId = param.getInteger("pJobId");
    	
    	List<Job> jobList = iJobService.list();
    	Integer maxPJobId = 0;
    	for (int index = 0; index < jobList.size(); index++) {
    		if(jobList.get(index).getPJobId() < maxPJobId) {
    			throw new SystemException("0");
    		}
    	}
    	
    	if (jobId <= 0 || jobId == null) {
            throw new SystemException("1");
        }
    	if (deptId <= 0 || deptId == null) {
            throw new SystemException("2");
        }
    	if (!StringUtils.hasLength(name)) {
            throw new SystemException("3");
        }
    	if (pJobId <= 0 || pJobId == null) {
            throw new SystemException("4");
        }
    	
    	Job job = new Job();
    	job.setJobId(jobId);
        job.setDeptId(deptId);
        job.setName(name);
        job.setPJobId(pJobId);
        QueryWrapper<Job> qWrapper = new QueryWrapper<Job>();
        qWrapper.eq("job_id", jobId);
    	Boolean statusBoolean = iJobService.update(job,qWrapper);
    	
        return ResultInfo.success();
    }



    /**
     * key: "/dept/job/info", 朱禹成
     * @param jobId
     * @return
     */
    @Transactional
    public ResultInfo deleteJob(Integer jobId) {
    	if(null == jobId) {
    		throw new SystemException("1");
    	}

    	List<Emp> empList = deptMapper.selectEmpJob();
    	if(!empList.isEmpty() || empList.size() != 0) {
    		throw new SystemException("请先处理该职位下员工");
    	}
    	
    	QueryWrapper<Emp> empQueryWrapper = new QueryWrapper<Emp>();
    	empQueryWrapper.eq("statu", "OUT");
    	List<Emp> empStatusList = iEmpService.list(empQueryWrapper);
    	if(!empStatusList.isEmpty() || empStatusList.size() != 0) {
    		throw new SystemException("该职位下员工为生效状态");
    	}

    	QueryWrapper<Job> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("p_job_id",jobId);
    	List<Job> jobList = iJobService.list(queryWrapper);
    	if(!jobList.isEmpty() || jobList.size() != 0) {
    		throw new SystemException("该职位不可删除");
    	}
    	
    	Boolean statusBoolean = iJobService.removeById(jobId);
    	
        return ResultInfo.success();
    }





}
